package com.zcxy.fast.handler;


import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.zcxy.fast.anotation.Dict;
import com.zcxy.fast.util.SysdictUtil;
import com.zcxy.fast.utils.StringUtils;

import java.io.IOException;

/**
 * 字典类型序列化
 * @author zcc
 */

public class DictSerializer extends StdSerializer<String> implements ContextualSerializer {

    private String dictCode;

    public DictSerializer() {
        super(String.class);
    }
    public DictSerializer(String  dictCode) {
        super(String.class);
        this.dictCode = dictCode;
    }
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
        Dict annotation = property.getAnnotation(Dict.class);
        return new DictSerializer(annotation.value());
    }
    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        String  name=gen.getOutputContext().getCurrentName();
        gen.writeString(value);
        if(StringUtils.isNotEmpty(value)){
            gen.writeObjectField(name+"_dict", SysdictUtil.getSysdictValue(this.dictCode,value));
        }
    }
}
